package org.ysh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.ysh.domain.RoleResource;
import org.ysh.service.ResourceService;
import org.ysh.service.RoleResourceService;
import org.ysh.vo.LayuiTreeNodeVo;
import org.ysh.vo.R;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/system/resource")
public class ResourceController {

    @Resource
    ResourceService resourceService;

    @Resource
    RoleResourceService roleResourceService;

    // 权限页面
    @RequestMapping("/permission")
    public ModelAndView permission(Integer roleId) {
        ModelAndView modelAndView = new ModelAndView("/system/role/permission");
        modelAndView.addObject("roleId",roleId);
        return modelAndView;
    }

    /**
     * 获取权限树
     * @param roleId
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    public List<LayuiTreeNodeVo> getResources(Integer roleId){
        RoleResource roleResource = new RoleResource();
        roleResource.setRoleId(roleId);
        List<RoleResource> roleResources = roleResourceService.findByPage(roleResource);
        org.ysh.domain.Resource resource = new org.ysh.domain.Resource();
        resource.setType( org.ysh.domain.Resource.RESOURCE_TYPE_MENU);
        return LayuiTreeNodeVo.buildTree(resourceService.findByPage(resource),roleResources);
    }

    /**
     * 设置角色的权限
     * @param roleId
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("/edit_permission")
    public R<?> editPermission(Integer roleId,@RequestParam("ids[]") Integer[] ids){
        roleResourceService.saveRoleResource(roleId,ids);
        return R.ok();
    }


    /**
     * 获取菜单下的按钮资源
     * @param menuCode
     * @return
     */
    @ResponseBody
    @GetMapping("/button_resource")
    public R<?> findButtonResource(String menuCode,Integer roleId) {
        org.ysh.domain.Resource resource = new org.ysh.domain.Resource();
        resource.setType(org.ysh.domain.Resource.RESOURCE_TYPE_BUTTON);
        resource.setParentCode(menuCode);
        RoleResource roleResource = new RoleResource();
        roleResource.setRoleId(roleId);
        List<RoleResource> roleResources = roleResourceService.findByPage(roleResource);
        return R.ok(LayuiTreeNodeVo.buildTree(menuCode,resourceService.findByPage(resource),roleResources));
    }

}
